package test;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EntityUtils;


public class MyHttp {

	private static HttpClient httpClient;

	public static HttpClient getHttpClient() {
		if (httpClient == null) {

			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams
					.setUserAgent(params,
							"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0");
			HttpConnectionParams.setConnectionTimeout(params, 5000);
			ConnManagerParams.setTimeout(params, 5000);
			ConnManagerParams.setMaxTotalConnections(params, 100);
			ConnManagerParams.setMaxConnectionsPerRoute(params,
					new ConnPerRouteBean(100));
			SchemeRegistry schreg = new SchemeRegistry();
			schreg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			ClientConnectionManager cManager = new ThreadSafeClientConnManager(
					params, schreg);
			httpClient = new DefaultHttpClient(cManager, params);
		}

		return httpClient;
	}

	public static HttpResponse getResponse(HttpClient httpClient,
			HttpGet httpGet)  {
		httpGet.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
		httpGet.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
		httpGet.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0");
		httpGet.setHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
		httpGet.setHeader("Accept-Encoding", "gzip");
		httpGet.setHeader("Connection", "keep-alive");
		HttpResponse response = null;
		int retryTime = 3;
		int i = 0;
		while (i < retryTime) {
			try {
				response = httpClient.execute(httpGet);
				int statusCode = response.getStatusLine().getStatusCode();
				if (statusCode != HttpStatus.SC_OK
						&& statusCode != HttpStatus.SC_MOVED_TEMPORARILY)
						i++;
				else {
					break;
				}

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (response == null)
				i++;
		}

		return response;
	}

	public static String getLocationUrl(HttpClient client, HttpPost httpPost)
			 {
		httpPost.getParams()
				.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
		httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
		httpPost.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0");
		httpPost.setHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpPost.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
		httpPost.setHeader("Accept-Encoding", "gzip");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Host", "bbs.ctdsb.net");
		HttpResponse response = null;
		String locationUrl = null;
		try {
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
				locationUrl = response.getLastHeader("Location").getValue();
				return locationUrl;
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
		}

		return locationUrl;
	}

	private static byte[] gZipToByteArray(HttpEntity entity) throws IOException {
		InputStream instream;
		ByteArrayBuffer buffer;
		if (entity == null)
			throw new IllegalArgumentException("HTTP entity may not be null");
		instream = new GZIPInputStream(entity.getContent());
		if (entity.getContentLength() > 2147483647L)
			throw new IllegalArgumentException(
					"HTTP entity too large to be buffered in memory");
		int i = (int) entity.getContentLength();
		if (i < 0)
			i = 4096;
		buffer = new ByteArrayBuffer(i);
		byte tmp[] = new byte[4096];
		int l;
		while ((l = instream.read(tmp)) != -1)
			buffer.append(tmp, 0, l);
		instream.close();
		return buffer.toByteArray();
	}

	public static byte[] getBytes(HttpResponse response) throws IOException {
		String acceptEcoding = null;
		if (response.getFirstHeader("Content-Encoding") != null) {
			acceptEcoding = response.getFirstHeader("Content-Encoding")
					.getValue();
			if (acceptEcoding.indexOf("gzip") != -1) {
				return gZipToByteArray(response.getEntity());
			}
		}
		return EntityUtils.toByteArray(response.getEntity());
	}
}
